//
//  AddCarVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2020/8/6.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "AddCarVC.h"
#import "DriverAddCell.h"
#import "DriverAddInPutCell.h"
#import "AddCarModel.h"
#import "LJDatePickerView.h"
#import "AddCarChooseDriverVC.h"
#import "AddCarChooseDriverModel.h"
#import "AddCarTypeModel.h"
#import "StatusChangeCell.h"

@interface AddCarVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) AddCarModel *carModel;
@property (nonatomic, strong) NSMutableArray <AddCarTypeModel *>*typeArray;
@property (nonatomic, strong) NSMutableArray <AddCarTypeModel *>*modelArray;

@end

@implementation AddCarVC

-(NSMutableArray<AddCarTypeModel *> *)modelArray {
    if (!_modelArray) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(NSMutableArray<AddCarTypeModel *> *)typeArray {
    if (!_typeArray) {
        _typeArray = [NSMutableArray array];
    }
    return _typeArray;
}

-(AddCarModel *)carModel {
    if (!_carModel) {
        _carModel = [AddCarModel new];
    }
    return _carModel;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - 64 - BottomHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 30 - 92 - 15 - 30, 44)];
        [nextBtn setBackgroundColor:HexColorA(0x3D68EB, 0.1)];
        nextBtn.layer.masksToBounds = YES;
        nextBtn.layer.cornerRadius = 6;
        [nextBtn setTitle:@"保存并继续添加车辆" forState:0];
        [nextBtn setTitleColor:HexColor(0x3D68EB) forState:0];
        nextBtn.titleLabel.font = BoldFontOfSize(16);
        [nextBtn addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:nextBtn];
        
        UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(nextBtn.nim_right + 15, 10, 92, 44)];
        [saveBtn setBackgroundColor:Color_ThemeColor];
        saveBtn.layer.masksToBounds = YES;
        saveBtn.layer.cornerRadius = 6;
        [saveBtn setTitle:@"保存" forState:0];
        [saveBtn setTitleColor:HexColor(0xffffff) forState:0];
        saveBtn.titleLabel.font = BoldFontOfSize(16);
        [saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:saveBtn];
    }
    return _bottomView;
}

- (void)nextClick {
    [self requestForSav:NO];
}

- (void)saveClick {
    [self requestForSav:YES];
}

- (void)requestForSav:(BOOL)isPop {
    if (!self.carModel.num.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请填写车牌号"];
        return;
    }
    if (!self.carModel.run_num.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请填写行驶证号"];
        return;
    }
    if (!self.carModel.f_time_str.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择初次上牌时间"];
        return;
    }else {
        self.carModel.f_time = [TimeModel timeSecondIntervalFromDate:self.carModel.f_time_str withformatter:@"yyyy-MM-dd"];
    }
    if ([self.carModel.max_weight floatValue]<=0) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"最大装载重量需大于0"];
        return;
    }
    if ([self.carModel.max_volume floatValue]<=0) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"最大装载体积需大于0"];
        return;
    }
    if (!self.carModel.car_type_str.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择车辆种类"];
        return;
    }
    if (!self.carModel.car_info_str.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择车型"];
        return;
    }
    if (!self.carModel.make_car.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请输入制造商"];
        return;
    }
//    if (!self.carModel.driver_id.length) {
//        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择司机"];
//        return;
//    }
    self.carModel.sys_status = self.carModel.sys_status == 2 ? 2 : 1;
    [HttpRequest PostWithApi:LogisticsSupplierAddCarSure params:[self.carModel mj_keyValues] progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"保存成功" delayOperation:^{
                if (isPop) {
                    [weakself.rt_navigationController popViewControllerAnimated:YES];
                }else {
                    weakself.carModel = [AddCarModel new];
                    [weakself.tableView reloadData];
                }
            }];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加车辆";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self requestForType];
    [self requestForCarModel];
    if (self.vehicle_id.length) {
        [self requestForEditDetail];
    }
}

- (void)requestForEditDetail {
    [HttpRequest PostWithApi:LogisticsSupplierEditCarInfo_V_1_0 params:@{@"vehicle_id":self.vehicle_id} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.carModel.vehicle_id = [self.vehicle_id intValue];
            self.carModel.num = responseObject[@"num"];
            self.carModel.run_num = responseObject[@"runNum"];
            self.carModel.f_time_str = responseObject[@"f_time"];
            self.carModel.f_time = [TimeModel timeSecondIntervalFromDate:self.carModel.f_time_str withformatter:@"yyyy-MM-dd"];
            self.carModel.max_weight = responseObject[@"max_weight"];
            self.carModel.max_volume = responseObject[@"max_volume"];
            if (![FactoryMethod isNull:responseObject[@"car_type"]]) {
                self.carModel.car_type_str = responseObject[@"car_type"];
            }
            if (![FactoryMethod isNull:responseObject[@"car_type_id"]]) {
                self.carModel.car_type = [responseObject[@"car_type_id"] intValue];
            }
            if (![FactoryMethod isNull:responseObject[@"car_info"]]) {
                self.carModel.car_info_str = responseObject[@"car_info"];
            }
            if (![FactoryMethod isNull:responseObject[@"car_info_id"]]) {
                self.carModel.car_info = [responseObject[@"car_info_id"] intValue];
            }
            self.carModel.make_car = responseObject[@"make_car"];
            self.carModel.gps = responseObject[@"gps"];
            self.carModel.colour_car = responseObject[@"colour_car"];
            self.carModel.remarks = responseObject[@"remarks"];
            self.carModel.sys_status = [responseObject[@"sys_status"] intValue];
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)requestForType {
    [HttpRequest GetWithApi:LogisticsSupplierCarType params:@{} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.typeArray = [AddCarTypeModel mj_objectArrayWithKeyValuesArray:responseObject];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)requestForCarModel {
    [HttpRequest PostWithApi:LogisticsSupplierCarModel_V_1_0 params:@{} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.modelArray = [AddCarTypeModel mj_objectArrayWithKeyValuesArray:responseObject];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        DriverAddCell *cell = [DriverAddCell DriverAddCellWithTableView:tableView];
        if (indexPath.row == 0) {
            cell.titleText = @"车牌号";
            cell.showLine = YES;
            cell.canClick = NO;
            cell.isMust = YES;
            cell.contentText = self.carModel.num;
            __weak_self;
            cell.cellBlock = ^(NSString * _Nonnull str) {
                weakself.carModel.num = str;
            };
        }else if (indexPath.row == 1) {
            cell.titleText = @"行驶证号";
            cell.showLine = YES;
            cell.canClick = NO;
            cell.isMust = YES;
            cell.contentText = self.carModel.run_num;
            __weak_self;
            cell.cellBlock = ^(NSString * _Nonnull str) {
                weakself.carModel.run_num = str;
            };
        }else if (indexPath.row == 2) {
            cell.titleText = @"初次上牌时间";
            cell.showLine = YES;
            cell.canClick = YES;
            cell.isMust = YES;
            cell.contentText = self.carModel.f_time_str;
        }else if (indexPath.row == 3) {
            cell.titleText = @"最大装载重量(kg)";
            cell.showLine = YES;
            cell.canClick = NO;
            cell.isMust = YES;
            cell.contentText = self.carModel.max_weight;
            __weak_self;
            cell.cellBlock = ^(NSString * _Nonnull str) {
                weakself.carModel.max_weight = str;
            };
        }else if (indexPath.row == 4) {
            cell.titleText = @"最大装载体积(m³)";
            cell.showLine = YES;
            cell.canClick = NO;
            cell.isMust = YES;
            cell.contentText = self.carModel.max_volume;
            __weak_self;
            cell.cellBlock = ^(NSString * _Nonnull str) {
                weakself.carModel.max_volume = str;
            };
        }else if (indexPath.row == 5) {
            cell.titleText = @"车辆种类";
            cell.showLine = YES;
            cell.canClick = YES;
            cell.isMust = YES;
            cell.contentText = self.carModel.car_type_str;
        }else if (indexPath.row == 6) {
            cell.titleText = @"车型";
            cell.showLine = YES;
            cell.canClick = YES;
            cell.isMust = YES;
            cell.contentText = self.carModel.car_info_str;
//            __weak_self;
//            cell.cellBlock = ^(NSString * _Nonnull str) {
//                weakself.carModel.car_info = str;
//            };
        }else if (indexPath.row == 7) {
            cell.titleText = @"制造商";
            cell.showLine = YES;
            cell.canClick = NO;
            cell.isMust = YES;
            cell.contentText = self.carModel.make_car;
            __weak_self;
            cell.cellBlock = ^(NSString * _Nonnull str) {
                weakself.carModel.make_car = str;
            };
//            else if (indexPath.row == 8) {
//                cell.titleText = @"默认司机";
//                cell.showLine = YES;
//                cell.canClick = YES;
//                cell.isMust = YES;
//                cell.contentText = self.carModel.driver_name;
//            }
        }else if (indexPath.row == 8) {
            cell.titleText = @"GPS";
            cell.showLine = YES;
            cell.canClick = NO;
            cell.isMust = NO;
            cell.contentText = self.carModel.gps;
            __weak_self;
            cell.cellBlock = ^(NSString * _Nonnull str) {
                weakself.carModel.gps = str;
            };
        }else if (indexPath.row == 9) {
            cell.titleText = @"颜色";
            cell.showLine = NO;
            cell.canClick = NO;
            cell.isMust = NO;
            cell.contentText = self.carModel.colour_car;
            __weak_self;
            cell.cellBlock = ^(NSString * _Nonnull str) {
                weakself.carModel.colour_car = str;
            };
        }
        return cell;
    }else if (indexPath.section == 1) {
        DriverAddInPutCell *cell = [DriverAddInPutCell DriverAddInPutCellWithTableView:tableView];
        return cell;
    }
    StatusChangeCell *cell = [StatusChangeCell StatusChangeCellWithTableView:tableView];
    cell.type = self.carModel.sys_status ? self.carModel.sys_status : 1;
    __weak_self;
    cell.changeBlock = ^{
        weakself.carModel.sys_status = weakself.carModel.sys_status == 1 ? 2 : 1;
        [weakself.tableView reloadData];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        DriverAddCell *cell = [DriverAddCell DriverAddCellWithTableView:tableView];
        return cell.height;
    }else if (indexPath.section == 1) {
        DriverAddInPutCell *cell = [DriverAddInPutCell DriverAddInPutCellWithTableView:tableView];
        return cell.height;
    }
    StatusChangeCell *cell = [StatusChangeCell StatusChangeCellWithTableView:tableView];
    return cell.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 2) {
            //选择初次上牌时间
            LJDatePickerView *picker = [[LJDatePickerView alloc] initWithDateMode:LJDatePickerViewModeDate];
            picker.currentDate = self.carModel.f_time_str.length ? self.carModel.f_time_str : [TimeModel stringFromDate:[NSDate date] andFormatter:@"yyyy-MM-dd"];
            __weak_self;
            [picker showWithDate:^(NSString * _Nonnull dateStr) {
                weakself.carModel.f_time_str = dateStr;
                weakself.carModel.f_time = [TimeModel timeSecondIntervalFromDate:weakself.carModel.f_time_str withformatter:@"yyyy-MM-dd"];
                [tableView reloadData];
            }];
        }else if (indexPath.row == 5) {
            //选择车辆种类
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            __weak_self;
            [self.typeArray enumerateObjectsUsingBlock:^(AddCarTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:obj.name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    weakself.carModel.car_type_str = obj.name;
                    weakself.carModel.car_type = obj.Id;
                    [weakself.tableView reloadData];
                }];
                [alert addAction:action1];
            }];
            UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:cancle];
            [weakself presentViewController:alert animated:YES completion:nil];
        }else if (indexPath.row == 6) {
            //选择车型
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            __weak_self;
            [self.modelArray enumerateObjectsUsingBlock:^(AddCarTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:obj.name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    weakself.carModel.car_info_str = obj.name;
                    weakself.carModel.car_info = obj.Id;
                    [weakself.tableView reloadData];
                }];
                [alert addAction:action1];
            }];
            UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:cancle];
            [weakself presentViewController:alert animated:YES completion:nil];
        }
//        if (indexPath.row == 8) {
//            //选择默认司机
//            if (self.carModel.num.length) {
//                AddCarChooseDriverVC *vc = [AddCarChooseDriverVC new];
//                vc.carNum = self.carModel.num;
//                AddCarChooseDriverModel *s_model = [AddCarChooseDriverModel new];
//                if (self.carModel.driver_id.length) {
//                    s_model.driver_id = self.carModel.driver_id;
//                }
//                vc.selectModel = s_model;
//                __weak_self;
//                vc.finishBlock = ^(AddCarChooseDriverModel * _Nonnull model) {
//                    weakself.carModel.driver_id = model.driver_id;
//                    weakself.carModel.driver_name = model.name;
//                    [weakself.tableView reloadData];
//                };
//                [self.rt_navigationController pushViewController:vc animated:YES];
//            }else {
//                [MBProgressHUD leShowFailedHUD:self.view message:@"请先输入车牌号"];
//            }
//        }
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 2) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
        view.backgroundColor = Color_backgroundColor;
        return view;
    }
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 2) {
        return 10;
    }
    return 0;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
